//
//  StoreViewController.m
//  Consume100
//
//  Created by eliot on 16/3/23.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "StoreViewController.h"
#import "PayFaceToFaceTableViewController.h"
#import "StoreTableViewCell.h"
#import "ProductViewController.h"
#import "MJrefresh.h"
#import "UIImageView+WebCache.h"
#import <CoreLocation/CoreLocation.h>
#define PI 3.1415926

@interface StoreViewController ()<UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong) UIView *topView;

@property (nonatomic, strong) UITableView *tableView;

/** 附近*/
@property (nonatomic, strong) UITableView *nearByTableView;
/** 附近-全部*/
@property (nonatomic, strong) UITableView *nearByAllTableView;
/** 美食广场*/
@property (nonatomic, strong) UITableView *foodSquareTableView;

/** 附近数据源*/
@property (nonatomic, strong) NSArray *nearByArr;
/** 附近数-全部据源*/
@property (nonatomic, strong) NSArray *nearByAllArr;
/** 种类数据源*/
@property (nonatomic, strong) NSArray *foodSquarelArr;
/** 背景视图*/
@property (nonatomic, strong) UIView *blackView;

/** 经度*/
@property (nonatomic, strong) NSString *longitude;
/** 纬度*/
@property (nonatomic, strong) NSString *latitude;

/** 位置*/
@property (nonatomic, strong) NSString *location;


@property (nonatomic, strong) NSMutableArray *storeArr;

@property (nonatomic, strong) CLLocationManager *locationManager;


@property (nonatomic, strong) NSDictionary *dd;

@end

@implementation StoreViewController


-(NSMutableArray *)storeArr {
    if (!_storeArr) {
        _storeArr = [NSMutableArray array];
    }
    return _storeArr;
}

-(UIView *)blackView {
    if (!_blackView) {
        //灰色背景
        self.blackView = [[UIView alloc] init];
        [self.view addSubview:_blackView];
        [self.blackView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
            make.top.mas_equalTo(self.nearByAllTableView.mas_bottom);
        }];
        
        self.blackView .backgroundColor = [UIColor colorWithRed:205/255.0 green:205/255.0 blue:205/255.0 alpha:0.6];
    }
    return _blackView;
}



-(NSArray *)foodSquarelArr {
    if (!_foodSquarelArr) {
        _foodSquarelArr = @[@"美食城",
                          @"商城商圈",
                          @"休闲娱乐",
                          @"KTV",
                          @"时尚丽人",
                          @"超市"];
    }
    return _foodSquarelArr;
}

- (UITableView *)nearByTableView {
    if (!_nearByTableView) {
        _nearByTableView = [[UITableView alloc] init];
        [self.view addSubview:_nearByTableView];
        _nearByTableView.delegate = self;
        _nearByTableView.dataSource = self;
        [_nearByTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(51);
            make.left.mas_equalTo(0);
            make.size.mas_equalTo(CGSizeMake(150, 264));
        }];
    }
    return _nearByTableView;
}
- (UITableView *)nearByAllTableView {
    if (!_nearByAllTableView) {
        _nearByAllTableView = [[UITableView alloc] init];
        [self.view addSubview:_nearByAllTableView];
        _nearByAllTableView.delegate = self;
        _nearByAllTableView.dataSource = self;
        _nearByAllTableView.backgroundColor = [UIColor colorWithRed:193/255.0 green:193/255.0 blue:193/255.0 alpha:1];
        [_nearByAllTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(150);
            make.top.mas_equalTo(51);
            make.right.mas_equalTo(0);
            make.height.mas_equalTo(264);
        }];
    }
    return _nearByAllTableView;
}

-(UITableView *)foodSquareTableView {
    if (!_foodSquareTableView) {
        _foodSquareTableView = [[UITableView alloc] init];
        _foodSquareTableView.delegate = self;
        _foodSquareTableView.dataSource = self;
        [self.view addSubview:_foodSquareTableView];
        [_foodSquareTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.top.mas_equalTo(51);
            make.height.mas_equalTo(264);
        }];
    }
    return _foodSquareTableView;
}


/**
 *  MARK：XIB创建
 *
 *  @return
 */

+(StoreViewController*)CreatStoreViewController{
    
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    StoreViewController *storeTableViewController=[story instantiateViewControllerWithIdentifier:@"StoreViewController"];
    
    return storeTableViewController;
}

- (UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
        [self.view addSubview:_topView];
        UILabel *lb1 = [[UILabel alloc] init];
        lb1.text = @"附近";
        lb1.textColor = [UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1];
        [_topView addSubview:lb1];
        [lb1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.view.frame.size.width/4 - 20);
            make.top.bottom.mas_equalTo(0);
            make.width.mas_equalTo(40);
        }];
        UIImageView *iv1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"more_down"]];
        [_topView addSubview:iv1];
        [iv1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(lb1.mas_right).mas_equalTo(2);
            make.top.mas_equalTo(19);
            make.size.mas_equalTo(CGSizeMake(12, 12));
        }];
        UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [_topView addSubview:btn1];
        btn1.backgroundColor = [UIColor clearColor];
        [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.bottom.mas_equalTo(0);
            make.width.mas_equalTo(self.view.frame.size.width / 2 - 1);
        }];
        
        UILabel *lb = [[UILabel alloc] init];
        [_topView addSubview:lb];
        lb.backgroundColor = [UIColor grayColor];
        [lb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(btn1.mas_right);
            make.top.bottom.mas_equalTo(0);
            make.width.mas_equalTo(1);
        }];
        UILabel *lb2 = [[UILabel alloc] init];
        lb2.text = self.storetypeLb;
        lb2.textColor = [UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1];
        [_topView addSubview:lb2];
        [lb2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(btn1.mas_right).mas_equalTo(self.view.frame.size.width/4 - 40);
            make.top.bottom.mas_equalTo(0);
            make.width.mas_equalTo(80);
        }];
        UIImageView *iv2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"more_down"]];
        iv1.contentMode = UIViewContentModeScaleAspectFit;
        iv2.contentMode = UIViewContentModeScaleAspectFit;
        [_topView addSubview:iv2];
        [iv2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(lb2.mas_right).mas_equalTo(2);
            make.top.mas_equalTo(19);
            make.size.mas_equalTo(CGSizeMake(12, 12));
        }];
        lb1.font = [UIFont systemFontOfSize:19];
        lb2.font = [UIFont systemFontOfSize:19];
        UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
        [_topView addSubview:btn2];
        btn2.backgroundColor = [UIColor clearColor];
        [btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.top.bottom.mas_equalTo(0);
            make.width.mas_equalTo(self.view.frame.size.width / 2 - 1);
        }];
        
        [btn1 addTarget:self action:@selector(clickNearByBtn) forControlEvents:UIControlEventTouchUpInside];
        [btn2 addTarget:self action:@selector(clcikFoodSquareBtn) forControlEvents:UIControlEventTouchUpInside];
        
        
    }
    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = [UIColor grayColor];
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(50);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(1);
    }];
    
    return _topView;
    
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        [self.view addSubview:_tableView];
        [_tableView registerNib:[UINib nibWithNibName:@"StoreTableViewCell" bundle:nil] forCellReuseIdentifier:@"StoreTableViewCell"];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(51);
            make.left.right.bottom.mas_equalTo(0);
        }];
    }
    return _tableView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"店铺";
    self.tableView.hidden = NO;
    self.topView.hidden = NO;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.navigationController.navigationBar.translucent = NO;
    self.tableView.tableFooterView = [[UIView alloc] init];
    /** 初始化定位*/
    [self initializeLocationService];
    
   
    
    
    
    
    
    
    

}


- (void)initializeLocationService {
    // 初始化定位管理器
    _locationManager = [[CLLocationManager alloc] init];
    // 设置代理
    _locationManager.delegate = self;
    // 设置定位精确度到米
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置每隔10米重新定位
   // _locationManager.distanceFilter = kCLDistanceFilterNone;
    _locationManager.distanceFilter = 10.0f;
    [_locationManager requestAlwaysAuthorization];//这句话ios8以上版本使用。
    // 开始定位
    [_locationManager startUpdatingLocation];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
        
        [_locationManager requestWhenInUseAuthorization];  //调用了这句,就会弹出允许框了.
    }
    
}

#pragma mark - 定位代理
//- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
//{
//    //将经度显示到label上
//    self.longitude = [NSString stringWithFormat:@"%lf", newLocation.coordinate.longitude];
//    //将纬度现实到label上
//    self.latitude = [NSString stringWithFormat:@"%lf", newLocation.coordinate.latitude];
//    // 获取当前所在的城市名
//    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//    //根据经纬度反向地理编译出地址信息
//    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
//        if (array.count > 0){
//            CLPlacemark *placemark = [array objectAtIndex:0];
//            //将获得的所有信息显示到label上
//            self.location = placemark.name;
//            //获取城市
//            NSString *city = placemark.locality;
//            if (!city) {
//                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
//                city = placemark.administrativeArea;
//            }
//        }
//        else if (error == nil && [array count] == 0)
//        {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [MBProgressHUD showError:@"定位失败，请移驾网络好的地方"];
//            });
//        }
//        else if (error != nil)
//        {
//            NSLog(@"An error occurred = %@", error);
//        }
//    }];
//    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
//    [manager stopUpdatingLocation];
//}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    
    
    CLLocation * currLocation = [locations lastObject];
    
     //将纬度现实到label上
    self.longitude = [NSString stringWithFormat:@"%.3f", currLocation.coordinate.longitude];
   
    self.latitude = [NSString stringWithFormat:@"%.3f", currLocation.coordinate.latitude];
    
    
    AFHTTPSessionManager *afManager = [AFHTTPSessionManager manager];
    afManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    afManager.requestSerializer.timeoutInterval = 5;
    self.cityName = [self.cityName stringByReplacingOccurrencesOfString:@"市" withString:@""];
    NSDictionary *dic = @{@"latitude":self.latitude, @"longitude":self.longitude,@"district":[NSString stringWithFormat:@"%d", self.district], @"page":@"1", @"cityName":self.cityName};
   
    NSString *baseUrl = [NSString stringWithFormat:@"%@getBusinessByState.jhtml", MyBaseURL];
    [afManager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSArray *arr = dic[@"businessJson"];
            self.dd = arr.firstObject;
            self.nearByArr = self.dd.allKeys;
            NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]);
            self.nearByArr = dic[@"businessClz"];
            NSString *first = self.nearByArr[0];
            self.nearByAllArr = dic[first];
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
    
    NSLog(@"%@",[NSString stringWithFormat:@"%.3f",currLocation.coordinate.latitude]);
    NSLog(@"%@",[NSString stringWithFormat:@"%.3f",currLocation.coordinate.longitude]);
    [manager stopUpdatingLocation];
}

#pragma mark - tableView (tableViewDelegate/tableViewDataSource)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        return self.storeArr.count;
    }else if(tableView == self.nearByTableView){
        return self.nearByArr.count;
    }else if (tableView == self.foodSquareTableView) {
    
        return 6;
    }else {
    
        return self.nearByAllArr.count;
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.tableView) {
        StoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StoreTableViewCell" forIndexPath:indexPath];
        cell.iconIV.layer.cornerRadius = 10;
        cell.iconIV.layer.masksToBounds = YES;
        NSDictionary *dic = self.storeArr[indexPath.row];
        [cell.iconIV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.188:8080%@",dic[@"businessImg"]]]];
        cell.nameLb.text = dic[@"businessName"];
        cell.scoreLb.hidden = YES;
        cell.personNumLb.hidden = YES;
        cell.distanceLb.text = [NSString stringWithFormat:@"%ld", [dic[@"m"] longValue]];

        return cell;
    }else if(tableView == self.nearByTableView) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"nearByCell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"nearByCell"];
            if (indexPath.row < self.nearByArr.count) {
               cell.textLabel.text = self.nearByArr[indexPath.row];
            }
        }
        return cell;
    }else if(tableView == self.nearByAllTableView){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"nearByAllCell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"nearByAllCell"];
            if (indexPath.row < self.nearByAllArr.count) {
                cell.textLabel.text = self.nearByAllArr[indexPath.row];
            }
            cell.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
        }
        return cell;
        
    }else if(tableView == self.foodSquareTableView){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"foodSquarelByCell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"foodSquarelByCell"];
            if (indexPath.row < self.foodSquarelArr.count) {
                cell.textLabel.text = self.foodSquarelArr[indexPath.row];
            }
        }
        return cell;
    }else {
        return nil;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        return 135;
    }else {
        return 44;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        if (![self.storetypeLb  isEqual: @"美食城"]) {
            PayFaceToFaceTableViewController *vc = [PayFaceToFaceTableViewController CreatPayFaceToFaceTableViewController];
            [self creatNav:vc];
        }else {
            ProductViewController *vc = [ProductViewController CreatProductViewController];
            NSDictionary *dic = self.storeArr[indexPath.row];
            vc.shopId = dic[@"businessId"];
            [self creatNav:vc];
        }
    }else if(tableView == self.nearByAllTableView){
        self.nearByAllTableView.hidden = YES;
        self.nearByTableView.hidden = YES;
        self.foodSquareTableView.hidden = YES;
        self.blackView.hidden = YES;
    }else if (self.tableView == self.nearByTableView) {
        NSString *first = self.nearByArr[0];
        self.nearByAllArr = self.dd[first];
        [self.nearByAllTableView reloadData];
    }
}

/** 根据经纬度计算距离*/
+(double) LantitudeLongitudeDist:(double)lon1 other_Lat:(double)lat1 self_Lon:(double)lon2 self_Lat:(double)lat2{
    double er = 6378137; // 6378700.0f;
    //ave. radius = 6371.315 (someone said more accurate is 6366.707)
    //equatorial radius = 6378.388
    //nautical mile = 1.15078
    double radlat1 = PI*lat1/180.0f;
    double radlat2 = PI*lat2/180.0f;
    //now long.
    double radlong1 = PI*lon1/180.0f;
    double radlong2 = PI*lon2/180.0f;
    if( radlat1 < 0 ) radlat1 = PI/2 + fabs(radlat1);// south
    if( radlat1 > 0 ) radlat1 = PI/2 - fabs(radlat1);// north
    if( radlong1 < 0 ) radlong1 = PI*2 - fabs(radlong1);//west
    if( radlat2 < 0 ) radlat2 = PI/2 + fabs(radlat2);// south
    if( radlat2 > 0 ) radlat2 = PI/2 - fabs(radlat2);// north
    if( radlong2 < 0 ) radlong2 = PI*2 - fabs(radlong2);// west
    //spherical coordinates x=r*cos(ag)sin(at), y=r*sin(ag)*sin(at), z=r*cos(at)
    //zero ag is up so reverse lat
    double x1 = er * cos(radlong1) * sin(radlat1);
    double y1 = er * sin(radlong1) * sin(radlat1);
    double z1 = er * cos(radlat1);
    double x2 = er * cos(radlong2) * sin(radlat2);
    double y2 = er * sin(radlong2) * sin(radlat2);
    double z2 = er * cos(radlat2);
    double d = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2));
    //side, side, side, law of cosines and arccos
    double theta = acos((er*er+er*er-d*d)/(2*er*er));
    double dist  = theta*er;
    return dist;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.nearByAllTableView.hidden = YES;
    self.nearByTableView.hidden = YES;
    self.foodSquareTableView.hidden = YES;
    self.blackView.hidden = YES;
}

//点击附近
- (void)clickNearByBtn {
    self.nearByTableView.hidden = NO;
    self.nearByAllTableView.hidden = NO;
    self.foodSquareTableView.hidden = YES;
    self.blackView.hidden = NO;
}
//点击美食广场
- (void)clcikFoodSquareBtn {
   
    self.foodSquareTableView.hidden = NO;
    self.nearByTableView.hidden = YES;
    self.nearByAllTableView.hidden = YES;
    self.blackView.hidden = NO;
    
}


//创建模态导航控制器
-(void)creatNav:(UIViewController *)view{
    
    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:view];
    nav.navigationBar.barTintColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    view.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_back"] style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)dismiss {
    [self dismissViewControllerAnimated:YES completion:nil];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
